import {PassportStrategy} from "@nestjs/passport";
import {IStrategyOptions, Strategy} from "passport-local";
import {InjectModel} from "nestjs-typegoose";
import {User} from "@libs/db/models/user.model";
import {Model} from "mongoose";
import {HttpException, HttpStatus} from "@nestjs/common";
import * as bcrypt from 'bcryptjs'

export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(
      @InjectModel(User) private readonly UserModel: Model<User>
  ) {
    super({usernameField: 'username', passwordField: "password"} as IStrategyOptions)
  }

  async validate(username: string, password: string) {
    const user = await this.UserModel.findOne({username}).select('+password')
    if (!user) {
      throw new HttpException('用户名不存在', HttpStatus.FORBIDDEN)
    }
    const isValid = bcrypt.compareSync(password, user.password)
    if (!isValid) {
      throw new HttpException('密码错误', HttpStatus.FORBIDDEN)
    }

    return user
  }
}